<?php
/**
*
*
*/
class Yz_Application_Web
    extends Yz_Application_Abstract
    implements Yz_Application_Interface
{

    /** This MUST be present in order for LSB to work
     *  @var <self>
     */
    protected static $instance;

    /**
     * @var Yz_Router_Interface&
     */
    protected $router;


    /**
     *  @return Yz_Router_Interface
     */
    public static function selectRouter()
    {
        $i = static::$instance;
        $router =& $i->router;
        if (null === $router) {
            $router = $i->selectModule("router")->selectRouter();
        }
        return $router;
    }

    /**
    *   Perform some common (SAPI independent) basic initialization
    *
    */
    protected function __construct()
    {
        ob_start();
        parent::__construct();
        defined( 'YZ_WWW' ) or define( 'YZ_WWW', realpath('./www') . '/' );
    } // __construct

    protected function __invoke()
    {
        $rq = Yz_HTTP_Request::getInstance();
        $this
            ->readConfigForHost($rq->getHostname())
            ->selectRouter()
            ->routeRequest()
            ->sendResponse()
        ;
        return $this;
    }

    protected function displayErrorMessage( $message )
    {
        // dispose of any buffered data
        while( false !== ob_get_length() ) {
            ob_end_clean();
        } // while

        header( 'HTTP/1.1 500 Internal Server Error' );
        header( 'Content-Type: text/html; charset=utf-8' );
        include( 'Yz/templates/fatal-error.php' );
        return $this;
    }


    /**
    *
    */
    protected function readConfigForHost($host)
    {
        $host = strtr( $host, ':', '-'); // assuming host name is valid
        debug("Reading config for host {$host}");
        $myconfig = new Yz_Config( null, 'App.Config.Host-specific' );
        $configString = include( "config.{$host}.php" );
        if ( "" !== "$configString" ) {
            $config = Yz_Config_Loader::load( $configString, 'App.Config', $myconfig );
        }
        $this->config = $this->config->unionRecursive($myconfig);
        return $this;
    }

} // class


